<template>
    <div id="operational">
      <!-- <p>积分策略</p>
      <hr>
      <br>
      <div class="el-alert el-alert--info"><i class="el-alert__icon el-icon-information is-big"></i>
        <div class="el-alert__content">
          <p class="el-alert__description">当商品挂着某个积分策略时，即代表在购买时可用积分抵扣部分金额。</p>
          </div>
      </div>
      <br> -->
      <p class="mt20">设置积分策略</p>
      <hr>
      <div class="mt20">
        <el-row>
          <el-col :span='20'>
            <el-form :model="form" ref="form" :rules="rules" label-width="0">
              <el-form-item label="" prop='unitPointValue'>
                <p>设置积分成本 1积分= <el-input v-model="form.unitPointValue" style='width:100px;'></el-input> 元</p>
                <p>（1积分=0.03元，当1个积分的价值高于0.03元因此而产生的积分成本时，请将此部分积分成本加回至售价）</p>
              </el-form-item>
              <el-form-item label="" prop='maxRatio'>
                设置积分抵扣金额最高比例= <el-input v-model="form.maxRatio" style='width:100px;'></el-input> %
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
      <br>
      <p class="mt20">设置有效时间</p>
      <hr>
      <div class="mt20">
        <el-row>
          <el-col :span='8'>
            <el-form :model="form" ref="form" :rules="rules" label-width="100px">
              <el-form-item label="生效时间" prop='timeList'>
                <time-picker-group
                  :time-list = 'timeList'
                  type='campaignedit'
                  @updateTimeGroup = 'updateForm'
                ></time-picker-group>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
      <br>
      <p class="mt20">设置促销价格</p>
      <hr>
      <br>
      <div>
        <div>
          <el-button type="primary" icon="plus" @click='callPanel'>添加此活动关联的商品</el-button>
          <span>先选型所需关联的商品</span>
          </div>
      </div>
      <br>
      <integral-goods-table
        :product-list = 'productList'
        @updateProduct = 'changeProductList'
      ></integral-goods-table>
      <!-- 商品选择面板 -->
      <goods-select-panel
        ref='goodsSelectPanel'
        :prop-item = 'productList'
        @updateProduct = 'changeProductList'
      ></goods-select-panel>
      <integral-conflict-panel
        ref='integralConflictPanel'
      ></integral-conflict-panel>
      <br>
      <p style="text-indent:400px">
        <el-button type="primary" size="large" @click='submitForm'>提交</el-button>
      </p>
    </div>
</template>
<script>
import goodsSelectPanel from 'components/operational/goodsSelectPanel.vue'
import timePickerGroup from 'components/operational/timePickerGroup.vue'
import strategyPriceTable from 'components/operational/strategyPriceTable.vue'
import integralGoodsTable from 'components/operational/integralGoodsTable.vue'
import integralConflictPanel from 'components/operational/integralConflictPanel.vue'
import {
  savePointStrategySave,
  getPointStrategyById
} from 'src/api/index.js'
export default {
  beforeRouteEnter (to, from, next) {
    let query = to.query
    if (query.type && query.type === 'edit') {
      getPointStrategyById({
        id: query.id || ''
      }).then((res) => {
        let result = res.data
        if (result.code === 100) {
          result.data.maxRatio = result.data.maxRatio * 100
          next((vm) => {
            vm.editParam = result.data
            vm.id = query.id
          })
        } else {
          window.alert(result.message)
          next()
        }
      })
    } else {
      next()
    }
  },
  created () {
    this.$route.meta.breadcrumbData = [
      {
        butRule: '/operational',
        name: '营销管理'
      },
      {
        butRule: '/operational/integralEdit',
        name: '编辑积分策略'
      }
    ]
  },
  mounted () {
    if (this.$route.query.type && this.$route.query.type === 'edit') {
      this.$nextTick(() => {
        this.setEditParam(this.editParam)
      })
    }
  },
  data () {
    return {
      id: null,
      timeList: [],
      editParam: {},
      showPanel: false,
      productList: [],
      form: {
        unitPointValue: '',
        maxRatio: '',
        timeList: []
      },
      rules: {
        unitPointValue: [
          {required: true, message: '请设置积分成本'}
        ],
        maxRatio: [
          {required: true, message: '请设置积分抵扣金额最高比例'}
        ],
        timeList: [
          {
            required: true,
            validator: function (rule, value, callback) {
              if (value.length === 0) {
                callback(new Error('请设置有效生效时间'))
              }
              value.forEach((item) => {
                if (!item['effectBeginTime']) {
                  callback(new Error('请设置有效生效时间'))
                } else if (!item['effectEndTime']) {
                  callback(new Error('请设置有效生效时间'))
                }
              })
              callback()
            }
          }
        ]
      }
    }
  },
  watch: {
    'form.timeList': {
      deep: true,
      handler: function () {
        this.$refs.form.validateField('timeList')
      }
    }
  },
  methods: {
    setEditParam (editParam) {
      this.form.unitPointValue = editParam.unitPointValue
      this.form.maxRatio = editParam.maxRatio
      editParam.timeList.forEach((item) => {
        let start = new Date(parseFloat(item.startTime))
        let end = new Date(parseFloat(item.endTime))
        this.timeList.push({
          ...item,
          timePickerGroup: [start, end]
        })
      })
      editParam.productList.forEach((item) => {
        this.productList.push(item.productId)
      })
    },
    callPanel () {
      this.$refs.goodsSelectPanel.showPanel()
    },
    changeProductList (productList) {
      this.productList = productList
    },
    updateForm (timeList) {
      this.form.timeList = timeList
    },
    submitForm () {
      this.validate()
        .then((validateResult) => {
          let productList = []
          this.productList.forEach((item) => {
            productList.push({
              productId: item
            })
          })
          let timeList = []
          this.form.timeList.forEach((item) => {
            timeList.push({
              'startTime': item.effectBeginTime,
              'endTime': item.effectEndTime
            })
          })
          return savePointStrategySave({
            maxRatio: this.form.maxRatio / 100,
            productList,
            timeList,
            unitPointValue: this.form.unitPointValue - 0,
            id: this.id
          })
        })
        .then((res) => {
          return new Promise((resolve, reject) => {
            let result = res.data
            if (result.code === 100) {
              if (result.data.failProductList && result.data.failProductList.length > 0) {
                // 出现商品冲突的情况
                resolve({
                  failProductList: result.data.failProductList,
                  cacheKey: result.data.cacheKey
                })
              } else {
                this.$alert('修改成功', {
                  confirmButtonText: '确定',
                  callback: action => {
                    this.$router.push({
                      path: '/operational/integralList'
                    })
                  }
                })
              }
            } else {
              this.$alert(result.message)
            }
          })
        })
        .then(this.handleConflict)
        .catch((result) => {
        })
    },
    handleConflict ({failProductList, cacheKey}) {
      // 处理冲突的情况
      this.$refs.integralConflictPanel.callPanel(failProductList, cacheKey)
    },
    validate () {
      return new Promise((resolve, reject) => {
        this.$refs.form.validate(function (result) {
          if (result) {
            resolve(result)
          } else {
            reject(result)
          }
        })
      })
    }
  },
  components: {
    goodsSelectPanel,
    timePickerGroup,
    strategyPriceTable,
    integralGoodsTable,
    integralConflictPanel
  }
}
</script>
<style>
  #operational .el-alert__description {
    font-size:16px;
  }
</style>
